<?php
namespace app\common\libs;

/**
 * @author : SN
 * @time   : 2020/3/30 16:11
 * @des    : Jwt工具类
*/
class Jwt
{
    private static $key = "123456";
    //token过期时间
    private static $token_exp_time = 7200;
    //refresh_token过期时间
    private static $refresh_token_exp_time = 10 * 24 * 3600;

    /**
     * @author : SN
     * @time   : 2020/3/30 16:13
     * @des    : 生成token和refresh_token
     * @param $login_info 登录信息
     * @param bool $is_refresh 是否生成refresh_token
     * @return mixed
     */
    public static function jwt_encode($login_info, $is_refresh=false){

        $c_time = time();
        //$payload['iss'] = "";   //签发者 可以为空
        //$payload['aud'] = "";   //面象的用户，可以为空
        $payload['iat'] = $c_time;   //签发时间
        $payload['nbf'] = $c_time;   //在什么时候jwt开始生效
        $payload['exp'] = $c_time + self::$token_exp_time;   //token 过期时间
        $payload['u'] = $login_info;

        //生成$token
        $token = \Firebase\JWT\JWT::encode($payload, self::$key);
        $data['token'] = $token;
        $data['token_expire'] = self::$token_exp_time;

        //生成$refresh_token
        if ($is_refresh){
            $payload['exp'] = $c_time + self::$refresh_token_exp_time;   //refresh token 过期时间
            $refresh_token = \Firebase\JWT\JWT::encode($payload, self::$key);
            $data['refresh_token'] = $refresh_token;
            $data['refresh_token_expire'] = self::$refresh_token_exp_time;
        }

        return $data;
    }


    /**
     * @author : SN
     * @time   : 2020/3/30 16:16
     * @des    : 解析token
     * @param $token
     * @return object
     */
    public static function jwt_decode($token){
        return \Firebase\JWT\JWT::decode($token, self::$key, array('HS256'));
    }






}